//
//  LineChart.m
//  LineChartDemo
//
//  Created by sunbin on 2017/3/3.
//  Copyright © 2017年 Quanli. All rights reserved.
//

#import "LineChart.h"


static CGRect myFrame;
static CGRect myFrame;
static int count ,yCount;   // 点个数，x轴格子数  y轴格子数

// x轴每个格子宽度 y轴每个格子高度
static CGFloat everyX ,everyY;
// 整个图表高度  整个图表宽度
static CGFloat allH ,allW;
static CGFloat maxY;    // 最大的y值
#define kMargin 30

#define kYDataCount 5 //y轴平分5个


@interface LineChart()

//@property (weak, nonatomic) IBOutlet UIView *bigView;

// x轴值
@property (nonatomic, copy) NSArray *xValues;
// y轴值
@property (nonatomic, copy) NSArray *yValues;



@end

@implementation LineChart
{
    CGPoint prePoint ,nowPoint;
}

- (void)reloadData{
    [self layoutSubviews];
    [self setNeedsDisplay];
    
}

- (void)awakeFromNib{
    [super awakeFromNib];

}
- (void)layoutSubviews{
    [super layoutSubviews];

    // x y 坐标值上的数据获取
    if ([self.delegate respondsToSelector:@selector(xValues)]) {
        self.xValues = [self.delegate xValues];
    }
    
    if ([self.delegate respondsToSelector:@selector(yValues)]) {
        self.yValues = [self.delegate yValues];
    }

    
}

// 实例化
+ (instancetype)lineChartViewWithFrame:(CGRect)frame{
    LineChart *lineChartView = [[NSBundle mainBundle] loadNibNamed:@"LineChart" owner:self options:nil].lastObject;
    lineChartView.frame = frame;//设置大小
    myFrame = frame;

    return lineChartView;
}

- (void)drawRect:(CGRect)rect{
    [self drawChartWithLineChartType:LineChartType_Straight pointType:PointType_Circel];
    
}

- (void)clearsub{
    for (UIView *view in self.subviews) {
        if ([view isKindOfClass:[UILabel class]]) {
            [view removeFromSuperview];
        }
    }
    self.layer.sublayers = nil;//清理layer层


}

- (void)drawChartWithLineChartType:(LineChartType)lineType pointType:(PointType)pointType{
    
    [self clearsub];
    
    // 计算赋值
    [self doWithCalculate];

//    [self drawXYLine];

    
    [self drawLabels];
    
//    [self drawLines];
    
    [self drawFoldLineWithLineChartType:LineChartType_Straight];
    [self drawPointsWithPointType:PointType_Circel];

    [self drawValues];
}



#pragma mark - 计算
- (void)doWithCalculate{
    //判断是否数据是否齐全
    if (!self.xValues || !self.xValues.count || !self.yValues || !self.yValues.count) {
        return;
    }

    // 数据整理
    // 移除多余的值，计算点个数
    if (self.xValues.count > self.yValues.count) {
        //当x值大于y值 清理掉后面的值
        NSMutableArray * xArr = [self.xValues mutableCopy];
        for (int i = 0; i < self.xValues.count - self.yValues.count; i++){
            [xArr removeLastObject];
        }
        self.xValues = [xArr mutableCopy];
    }else if (self.xValues.count < self.yValues.count){
        NSMutableArray * yArr = [self.yValues mutableCopy];
        for (int i = 0; i < self.yValues.count - self.xValues.count; i++){
            [yArr removeLastObject];
        }
        self.yValues = [yArr mutableCopy];
    }

    //x周数据的个数
    count = (int)self.xValues.count;
    //确定 x周每段长度 左右间距30 获取x轴上的数据平分长度 注意此处值需从原点开始 因此数值有
    everyX = (CGFloat)(CGRectGetWidth(myFrame) - kMargin * 2) / (count-1);
    

    yCount = count <= kYDataCount ? count : kYDataCount;
    //确定 y周每段长度
    everyY =  (CGRectGetHeight(myFrame) - kMargin * 2) / yCount;

    
    //获取最大值y周数据
    maxY = CGFLOAT_MIN;
    for (int i = 0; i < count; i ++) {
        if ([self.yValues[i] floatValue] > maxY) {
            maxY = [self.yValues[i] floatValue];
        }
    }
    NSLog(@"maxY=%f" ,maxY);

    
    //确定图表大小
    allH = CGRectGetHeight(myFrame) - kMargin * 2;
    allW = CGRectGetWidth(myFrame) - kMargin * 2;

    
}


#pragma mark - 画X、Y轴
- (void)drawXYLine{
    
    
    // 创建UIBezierPath曲线
    UIBezierPath *path = [UIBezierPath bezierPath];
    
    [path moveToPoint:CGPointMake(kMargin, kMargin / 2.0 - 5)];//起始点
    
    [path addLineToPoint:CGPointMake(kMargin, CGRectGetHeight(myFrame) - kMargin)];//坐标00点 源点
    [path addLineToPoint:CGPointMake(CGRectGetWidth(myFrame) - kMargin / 2.0 + 5, CGRectGetHeight(myFrame) - kMargin)];
    
    // 加箭头
    [path moveToPoint:CGPointMake(kMargin - 5, kMargin/ 2.0 + 4)];
    [path addLineToPoint:CGPointMake(kMargin, kMargin / 2.0 - 4)];
    [path addLineToPoint:CGPointMake(kMargin + 5, kMargin/ 2.0 + 4)];
    
    [path moveToPoint:CGPointMake(CGRectGetWidth(myFrame) - kMargin / 2.0 - 4, CGRectGetHeight(myFrame) - kMargin - 5)];
    [path addLineToPoint:CGPointMake(CGRectGetWidth(myFrame) - kMargin / 2.0 + 5, CGRectGetHeight(myFrame) - kMargin)];
    [path addLineToPoint:CGPointMake(CGRectGetWidth(myFrame) - kMargin / 2.0 - 4, CGRectGetHeight(myFrame) - kMargin + 5)];
    
    
    //CAShapeLayer
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    layer.path = path.CGPath;
    layer.strokeColor = [UIColor brownColor].CGColor;
    layer.fillColor = [UIColor clearColor].CGColor;//填充色
    layer.lineWidth = 2.0;
    [self.layer addSublayer:layer];

}








#pragma mark - 添加label xy轴上的数据
- (void)drawLabels{
    
    //Y轴=对应参数值
    for(int i = 0; i <= yCount; i ++){
        UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, kMargin  + everyY * i - everyY / 2, kMargin - 1, everyY)];
        lbl.textColor = [UIColor blackColor];
        lbl.font = [UIFont systemFontOfSize:12];
        //lbl.backgroundColor = [UIColor brownColor];
        lbl.textAlignment = NSTextAlignmentRight;
        lbl.text = [NSString stringWithFormat:@"%d", (int)(maxY / yCount * (yCount - i)) ];
        
//        [self.bigView addSubview:lbl];
    }
    
    // X轴=对应参数值
    for(int i = 0; i < count; i ++){
        
        UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(kMargin + everyX * i - everyX / 2, CGRectGetHeight(myFrame) - kMargin, everyX, kMargin)];
        
        lbl.textColor = [UIColor blackColor];
        lbl.font = [UIFont systemFontOfSize:12];
        //lbl.backgroundColor = [UIColor brownColor];
        lbl.textAlignment = NSTextAlignmentCenter;
        lbl.text = [NSString stringWithFormat:@"%@", self.xValues[i]];
        
        [self addSubview:lbl];
    }
    
}


#pragma mark - 画网格
- (void)drawLines{
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    // 横线
    for (int i = 0; i < yCount; i ++) {
        [path moveToPoint:CGPointMake(kMargin , kMargin + everyY * i)];
        [path addLineToPoint:CGPointMake(kMargin + allW ,  kMargin + everyY * i)];
    }
    // 竖线
    for (int i = 1; i <= count; i ++) {
        [path moveToPoint:CGPointMake(kMargin + everyX * i, kMargin)];
        [path addLineToPoint:CGPointMake( kMargin + everyX * i,  kMargin + allH)];
    }
    
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    layer.path = path.CGPath;
    layer.strokeColor = [UIColor whiteColor].CGColor;
    layer.fillColor = [UIColor clearColor].CGColor;
    layer.lineWidth = 0.5;
    [self.layer addSublayer:layer];
    
}





#pragma mark - 画点
- (void)drawPointsWithPointType:(PointType)pointType{
    // 画点
    switch (pointType) {
            //小方框
        case PointType_Rect:
            
            for (int i = 0; i < count; i ++) {
                //确定 小点的位置
                
                CGPoint point = CGPointMake(kMargin + everyX * (i + 1) , kMargin + (1 - [self.yValues[i] floatValue] / maxY ) * allH);
                CAShapeLayer *layer = [[CAShapeLayer alloc] init];
                layer.frame = CGRectMake(point.x - 2.5, point.y - 2.5, 5, 5);
                layer.backgroundColor = [UIColor redColor].CGColor;
                [self.layer addSublayer:layer];
            }
            break;
            
        case PointType_Circel:
            //小圆点
            for (int i = 0; i < count; i ++) {
                //确定 小点的位置
                CGPoint point = CGPointMake(kMargin + everyX * (i) , kMargin + (1 - [self.yValues[i] floatValue] / maxY ) * allH);
                
                UIBezierPath *path = [UIBezierPath
                                      
                                      //    方法1                          bezierPathWithArcCenter:point radius:2.5 startAngle:0 endAngle:M_PI * 2 clockwise:YES];
                                      
                                      //    方法2
                                      bezierPathWithRoundedRect:CGRectMake(point.x - 2.5, point.y - 2.5, 5, 5) cornerRadius:2.5];
                
                
                CAShapeLayer *layer = [CAShapeLayer layer];
                layer.path = path.CGPath;
                layer.strokeColor = [UIColor PointType_Circel].CGColor;
                layer.fillColor = [UIColor PointType_Circel].CGColor;
                [self.layer addSublayer:layer];
            }
            
            break;
    }
}



#pragma mark - 画折线\曲线
- (void)drawFoldLineWithLineChartType:(LineChartType)type{
    
    
    switch (type) {
        case LineChartType_Straight:
            for (int i = 0; i <= count; i ++) {
                
                
                if (i==0) {
                    UIBezierPath *path = [UIBezierPath bezierPath];

                    CGPoint moveToPoint = CGPointMake(kMargin, kMargin + (1 - [self.yValues.firstObject floatValue] / maxY) * allH);
                    CGPoint addLineToPoint = CGPointMake(0, kMargin + (1 - [self.yValues.firstObject floatValue] / maxY) * allH);

                    [path moveToPoint:moveToPoint];
                    [path addLineToPoint:addLineToPoint];
                    
                    [self path:path isShowDottedLine:YES];

                }else if (0<i && i < count-1){
                    UIBezierPath *path = [UIBezierPath bezierPath];

                    [path moveToPoint:CGPointMake(kMargin+everyX *(i-1), kMargin + (1 - [self.yValues[i-1] floatValue] / maxY) * allH)];
                    [path addLineToPoint:CGPointMake(kMargin+everyX * i, kMargin + (1 - [self.yValues[i] floatValue] / maxY) * allH)];
                    [self path:path isShowDottedLine:NO];

                }else if (i==count-1){
                    UIBezierPath *path = [UIBezierPath bezierPath];
                    [path moveToPoint:CGPointMake(kMargin+everyX *(i-1), kMargin + (1 - [self.yValues[i-1] floatValue] / maxY) * allH)];
                    [path addLineToPoint:CGPointMake(kMargin+everyX * i, kMargin + (1 - [self.yValues[i] floatValue] / maxY) * allH)];
                    
                    [self path:path isShowDottedLine:YES];
                }
                else if (i == count){
                    UIBezierPath *path = [UIBezierPath bezierPath];                    
                    CGPoint point = CGPointMake(kMargin + everyX * (count-1) , kMargin + (1 - [self.yValues[count-1] floatValue] / maxY ) * allH);
                    
                    [path moveToPoint:point];
                    
                    [path addLineToPoint:CGPointMake([UIScreen mainScreen].bounds.size.width, kMargin + (1 - [self.yValues[count-1] floatValue] / maxY) * allH)];

                    [self path:path isShowDottedLine:YES];

                }

            }
            break;
        case LineChartType_Curve:
            
//            [path moveToPoint:CGPointMake(0, kMargin + (1 - [self.yValues.firstObject floatValue] / maxY) * allH)];
//
//            for (int i = 0; i <= count; i ++) {
//
//                if (i == 0) {
//                    [path addLineToPoint:CGPointMake(kMargin,kMargin + (1 - [self.yValues.firstObject floatValue] / maxY) * allH)];
//
//
//                }else if (i<count) {
//                    
//                    
//                    prePoint = CGPointMake(  everyX * i, kMargin + (1 - [self.yValues[i-1] floatValue] / maxY) * allH);
//                    
//                    nowPoint = CGPointMake( kMargin+everyX * i, kMargin + (1 - [self.yValues[i] floatValue] / maxY) * allH);
//                    
//                    // 两个控制点的两个x中点为X值，preY、nowY为Y值；
//                    [path addCurveToPoint:nowPoint controlPoint1:CGPointMake((nowPoint.x+prePoint.x)/2, prePoint.y) controlPoint2:CGPointMake((nowPoint.x+prePoint.x)/2, nowPoint.y)];
//                    
//
//                }else{
//                    // 注意前后一项为0 且虚线
//
//                    NSLog(@"prePoint=%@  nowPoint=%@" ,NSStringFromCGPoint(prePoint) ,NSStringFromCGPoint(nowPoint));
//                    [path addLineToPoint:CGPointMake(nowPoint.x+kMargin, nowPoint.y)];
//
//                }
//                
//            }
            
            
            break;
            
    }
    
    
    
    
    

}


- (void)path:(UIBezierPath *)path isShowDottedLine:(BOOL)dottedLine{
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    
    layer.path = path.CGPath;
    
    if (dottedLine) {
        layer.lineDashPattern = @[@1, @1];//画虚线
    }
    

    layer.strokeColor = [UIColor lineColor].CGColor;
    layer.fillColor = [UIColor clearColor].CGColor;
    
    [self.layer addSublayer:layer];
    

}

#pragma mark - 显示数据
- (void)drawValues{
    for (int i = 0; i < count; i ++) {

        CGPoint nowPoint = CGPointMake(kMargin + everyX * (i), kMargin + (1 - [self.yValues[i] floatValue] / maxY) * allH);
        UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(nowPoint.x - everyX/2.0-5, nowPoint.y - 20, everyX+10, 20)];
        lbl.textColor = [UIColor grayColor];
        lbl.textAlignment = NSTextAlignmentCenter;
        lbl.text = [NSString stringWithFormat:@"%@",self.yValues[i]];
        lbl.font = [UIFont systemFontOfSize:14];
        lbl.adjustsFontSizeToFitWidth = YES;
        [self addSubview:lbl];
    }
    
}


@end
